package com.xiaobai.units;

import com.xiaobai.service.addition.HealthReportService_v2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-11-20
 **/

@Slf4j
public class IpProxyUtil {

    private static String PROXY_URL = "http://tiqu.pyhttp.taolop.com/getip?count=1&neek=7373&type=1&yys=0&port=1&sb=&mr=1&sep=1&city=440100&time=2";

    private static Date lastUpdateTime;
    private static ProxyAddress proxyAddress;

    public static class ProxyAddress {
        private ProxyAddress(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }
        private String ip;
        private int port;
        public String getIp() {
            return ip;
        }

        public int getPort() {
            return port;
        }
    }

    public static ProxyAddress getItem() {
        if (proxyAddress == null || DateUtils.addMinutes(lastUpdateTime, 5).getTime() < new Date().getTime()) {
            log.info("更新代理IP");
            updateItem();
        }
        return proxyAddress;
    }

    public static synchronized void updateItem() {
        if (lastUpdateTime != null && DateUtils.addSeconds(new Date(), -2).getTime() < lastUpdateTime.getTime()) {
            // 两秒前更新过,防止API接口QPS限制
            log.info("QPS更新限制");
            try {
                // 刚更新的代理IP不可用,会导致2S内无限重试,所以这里睡眠1s防止短时间内重复走到这里
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return;
        }
        HttpGet httpGet = new HttpGet(PROXY_URL);
        try (CloseableHttpResponse rsp = HealthReportService_v2.httpclient.execute(httpGet);){
            String content = EntityUtils.toString(rsp.getEntity());
            if (StringUtils.isBlank(content) || content.contains("您的余额不足")) {
                proxyAddress = null;
                log.info("代理IP没钱了");
                return;
            }
            String[] split = content.split(":");
            proxyAddress = new ProxyAddress(split[0], Integer.parseInt(split[1].substring(0, split[1].length() - 2)));
            lastUpdateTime = new Date();
            log.info("更新IP代理池");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("代理IP更新失败");
            proxyAddress = null;
        }
    }

    public static void main(String[] args) {
        String filePath = "D:\\python_project\\pythonProject\\dataset\\train\\AAAA_1637490625.png";
        File file = new File(filePath);
        file.renameTo(new File("D:\\python_project\\pythonProject\\dataset\\train\\QQQQ_1637490625.png"));
    }

}
